#!/usr/bin/python  
#-*-coding:utf-8-*-

#version: 0.1

import sys
import os
import shutil
import stat
import json
import re
import copy
import codecs
import argparse
from xml.dom import minidom
from datetime import datetime
import pdb
import time
        
class BaseFunction(object):
    def __init__(self):
        print "Class init"
    
    def copy(self, src, dst):
        ''' Copy a file or a whole directory to destination folder
        '''
        if os.path.isdir(src):
            for item in os.listdir(src):
                src_path = os.path.join(src, item)
                dst_path = os.path.join(dst, item)
                if os.path.isfile(src_path) and not item.startswith('.'):
                    self.copy(src_path, dst_path)
                elif os.path.isdir(src_path) and item != '.svn':
                    if not os.path.isdir(dst_path):
                        os.makedirs(dst_path)
                    self.copy(src_path, dst_path)
        elif os.path.isfile(src):
            if os.path.isdir(dst):
                dst = os.path.join(dst, os.path.basename(src))
            elif not os.path.isdir(os.path.dirname(dst)):
                os.makedirs(os.path.dirname(dst))
            self.backup(dst)
            shutil.copy(src, dst)
        else:
            print 'Warning: Try to copy a non-existent file: ' + src
                
    def remove(self, path):
        ''' Remove a file or a whole directory
        '''
        if os.path.isdir(path):
            for root, dirs, files in os.walk(path, topdown=False):
                for name in files:
                    file_name = os.path.join(root, name)
                    os.chmod(file_name, stat.S_IWUSR)
                    os.remove(file_name)
                for name in dirs:
                    os.rmdir(os.path.join(root, name))
            os.rmdir(path);
        elif os.path.isfile(path):
            os.remove(path)
        else:
            print 'Warning: Try to remove a non-existent file: ' + path
    
    def rename(self, src, dst):
        ''' Rename a file to a new name
        '''
        if os.path.exists(dst):
            self.remove(dst)
        self.backup(src)
        self.backup(dst)
        os.renames(src, dst)
        
    def replace(self, path, old, new):
        ''' Find and replace strings in a file or directory
        '''
        old = self._realpath(old)
        new = self._realpath(new)
        if os.path.isdir(path):
            for root, dirs, files in os.walk(path, topdown=False):
                for file in files:
                    file_path = os.path.join(root, file)
                    if file_path.find('.svn') == -1:
                        self._replace_file(file_path, old, new)
        elif os.path.isfile(path):
            self._replace_file(path, old, new)
        else:
            print 'Warning: Nothing to be replaced, can not find %s!' % path
			
    def insert(self, path_src, path_dest, pos):
        ''' Insert the contents form a file to another file			
		    @path_src   the path of source file
            @path_dest  the path of destination file			
			@pos        the position of insert		
		'''
        file = open(path_dest,"r")
        fileadd = open(path_src,"r")
        content = file.read()
        contentadd = fileadd.read()
        file.close()
        fileadd.close()
        pos = content.find(pos)
        if pos != -1:
            content = content[:pos] + contentadd + content[pos:]
            file = open(path_dest,"w")
            file.write(content)
            file.close
            
    def _replace_file(self, path, old, new):
        fp = codecs.open(path, 'r', 'utf-8')
        data = fp.read()
        data = data.replace(old, new)
        fp.close()
        fp = codecs.open(path, 'w', 'utf-8')
        fp.write(data)
        fp.close()
    
    def _is_in_dir(self, file, dir):
        ''' Check if a file is in a directory
        '''
        file_path = os.path.abspath(file)
        dir_path = os.path.abspath(dir)
        return file_path.find(dir_path) != -1
        
    @staticmethod
    def _get_num_of_cpu():
        try:
            if sys.platform == 'win32':
                if 'NUMBER_OF_PROCESSORS' in os.environ:
                    return int(os.environ['NUMBER_OF_PROCESSORS'])
            else:
                from numpy.distutils import cpuinfo
                return cpuinfo.cpu._getNCPUs()
        except Exception:
            print "Don't know CPU info, use default 1 CPU"
        return 1
    
            
# -------------- main --------------
if __name__ == '__main__':
    print "remove ------ src/Scene/Update";
    base = BaseFunction();
    base.remove("src/Scene/Update")
    
    print "remove ------ res/Configs/Update";
    base.remove("res/Configs/Update")
    
    print "remove ------ res/Configs/localURLConfig.json";
    base.remove("res/Configs/localURLConfig.json")

    print "remove ------ res/Configs/og_info.json";
    base.remove("res/Configs/og_info.json")

    print "remove ------ res/Configs/update_info.json";
    base.remove("res/Configs/update_info.json")

    print "remove ------ res/Update";
    base.remove("res/Update")

    print "remove ------ res/Texture/update_image.plist";
    base.remove("res/Texture/update_image.plist")

    print "remove ------ res/Texture/update_image.png";
    base.remove("res/Texture/update_image.png")

    #time.sleep(5);

    
